package mashuaiproject.mashuaiproject.interceptor;

import mashuaiproject.mashuaiproject.mapper.NotificationMapper;
import mashuaiproject.mashuaiproject.mapper.OtherMapper;
import mashuaiproject.mashuaiproject.mapper.UserMapper;
import mashuaiproject.mashuaiproject.model.Users;
import mashuaiproject.mashuaiproject.serivce.NotificationSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SessionIntercept implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NotificationSerivce notificationSerivce;
    @Autowired
    private OtherMapper otherMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        //登录进来的时候之后创吧用户的token放进cookies中，
        //然后用拦截器，查找当前用户的所有信息写进session
        if(cookies!=null){
            for (Cookie cookie:cookies){
                if(cookie.getName().equals("token")){
                    String token=cookie.getValue();
                    Users users=userMapper.findByToken(token);
                    if (users!=null){
                        request.getSession().setAttribute("user",users);
                       // Integer selectNoReadCount1= notificationMapper.selectNoReadCount(users.getId());//当前用户未读数量
                        Integer noReadConut=notificationSerivce.selectNoReadCount(users.getId());
                        request.getSession().setAttribute("noReadConut",noReadConut);//将未读数量放假session
                    }

                    break;
                }
            }
        }
        return true;//为true代表一直执行，false停止执行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
